package it.tukano.swingdeco.menubar;

import javax.swing.JMenu;
import javax.swing.JMenuBar;

public class JMenuBarExt extends JMenuBar {

    /* Serial version of this class */
    private static final long serialVersionUID = 0;

    /**
     * Instance initializer
     */
    public JMenuBarExt() {
    }

    /**
     * Show a jmenu. If there is a jmenu with the same label, merges the contents
     * of the new menu with the old one
     * @param menu the menu to add or merge
     * @return this
     */
    public JMenuBarExt addMenu(JMenu menu) {
        JMenu oldMenu = getMenuWithSameLabel(menu);
        if(oldMenu != menu) {
            transferItems(menu, oldMenu);
        } else {
            this.add(menu);
        }
        return this;
    }

    private JMenu getMenuWithSameLabel(JMenu menu) {
        int count = getMenuCount();
        for (int i= 0; i < count; i++) {
            JMenu m = getMenu(i);
            if(m != null && m.getText().equals(menu.getText())) {
                return m;
            }
        }
        return menu;
    }

    private void transferItems(JMenu from, JMenu to) {
        if(to.getItemCount() != 0) {
            to.addSeparator();
        }
        int itemCount = from.getItemCount();
        for (int i= 0; i < itemCount; i++) {
            to.add(from.getItem(i));
        }
    }
}
